<template>
  <!-- 此页面用一般用于企业微信和微信消息互通的时候，顾问已经服务完成后，顾问发送给用户的快捷页面入口 -->
  <page-wrap
    ref="pageWrap"
    hideTab
    title="评价反馈"
    :showTop="showTop"
    :dark="true"
    :callBackUrl="gotoMyTabUrl"
    :hideSafeArea="true"
    :bg-color="uNavColor"
  >
    <view class="out-wrapper" :style="'padding-top:' + navHeight + 'px;'">
      <view class="header-wrapper">
        <div class="header">
          <view class="question"> 您对顾问满意吗？ </view>
          <view class="consultant-info">
            <view class="avatar-box">
              <image class="avatar" :src="avatar || defaultAvatar"></image>
            </view>
            <view class="name-box">
              <view class="consultant-name">{{ consultantName }}</view>
            </view>
          </view>
        </div>
        <view class="rateCardContent">
          <view class="rateTitleRow">
            <view class="rateTitleCol"></view>
            <view class="rateTitleCol">很不满</view>
            <view class="rateTitleCol">不满</view>
            <view class="rateTitleCol">一般</view>
            <view class="rateTitleCol">满意</view>
            <view class="rateTitleCol">很满意</view>
          </view>
          <view
            class="rateContentRow"
            v-for="(item, index) in rateList"
            :key="item.rateType"
          >
            <view class="rateContentCol">{{ item.rateName }}</view>
            <view
              class="rateContentCol"
              v-for="(iconItem, iconIndex) in item.iconList"
              :key="index + iconIndex"
              @click="handleRateIconClick(item, index, iconItem, iconIndex)"
            >
              <img :src="iconItem" class="rateContentIcon" />
            </view>
          </view>
        </view>
      </view>
      <view class="callback-wrapper box">
        <view class="title">我要反馈</view>
        <view class="words">
          <u-field
            v-model="content"
            label-width="0"
            auto-height
            :field-style="fieldStyle"
            placeholder-style="color: #BFBFBF"
            placeholder="我想说点什么"
            type="textarea"
          >
          </u-field>
        </view>
        <view class="upload-wrap">
          <u-upload
            ref="uUpload"
            :max-size="4 * 1024 * 1024"
            max-count="9"
            :action="uploadAction"
            :before-upload="beforeUpload"
            upload-text="上传图片"
            :custom-btn="true"
            class="u-m-b-24"
            :file-list="photosArray"
            @on-uploaded="onUploaded"
          >
            <view
              slot="addBtn"
              class="slot-btn"
              hover-class="slot-btn__hover"
              hover-stay-time="150"
            >
              <image :src="uploadImg" mode="" class="upload-img" />
              <view class="tips">上传图片</view>
            </view>
          </u-upload>
        </view>
      </view>
      <view class="number-wrapper box">
        <view class="title">
          <text class="big">联系方式</text>
          <text class="small">注：手机号/微信号</text>
        </view>
        <view class="words">
          <u-field
            v-model="contact"
            label-width="0"
            auto-height
            :field-style="fieldStyle"
            placeholder-style="color: #BFBFBF"
            placeholder="请留下任意一个联系方式，方便联系您"
            type="textarea"
          >
          </u-field>
        </view>
      </view>
    </view>
    <view class="btn-bar">
      <u-button
        style="width: 100%"
        :loading="loading"
        shape="circle"
        type="primary"
        @click="reqAddConsultantRateDetail"
        >提交</u-button
      >
    </view>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
    <u-toast ref="uToast" />
  </page-wrap>
</template>

<script>
import {
  getRateTypeList,
  addConsultantRateDetail,
  getConsultantRate,
  addConsultantRate,
  getUserInfo,
  getConsultantBasicInfo
} from '@/api/modules/career.js';
import { uploadAction } from '@/api/index';
import PageWrap from '../../../components/PageWrap.vue';
import LoginDialog from '@/components/LoginDialog';
import ShareMixin from '@/mixins/share';
export default {
  components: { PageWrap, LoginDialog },
  mixins: [ShareMixin],
  data() {
    return {
      uploadAction,
      defaultAvatar: this.$imgBase + 'common/avatar_default.png',
      uploadImg: this.$imgBase + 'company/upload.png',
      gotoMyTabUrl: '/pages/userCenter/index',
      navHeight: getApp().globalData.navHeight,
      sharePath: '/pagesSub/userCenter/zhituRatePage/index',
      loaded: false,
      uNavColor: '#79e3f4',
      showTop: false,
      fieldStyle: {
        backgroundColor: '#fafafa',
        padding: '24rpx'
      },
      grayIconList: [
        this.$imgBase + 'careerPath/rateOneGray.png',
        this.$imgBase + 'careerPath/rateTwoGray.png',
        this.$imgBase + 'careerPath/rateThreeGray.png',
        this.$imgBase + 'careerPath/rateFourGray.png',
        this.$imgBase + 'careerPath/rateFiveGray.png'
      ],
      colorIconList: [
        this.$imgBase + 'careerPath/rateOneColor.png',
        this.$imgBase + 'careerPath/rateTwoColor.png',
        this.$imgBase + 'careerPath/rateThreeColor.png',
        this.$imgBase + 'careerPath/rateFourColor.png',
        this.$imgBase + 'careerPath/rateFiveColor.png'
      ],
      avatar: '',
      consultantName: '',
      rateList: [],
      photosArray: [],
      content: '',
      contact: '',
      isRated: false,
      personId: '',
      consultantId: '',
      isConsultant: false,
      userIsConsultant: false,
      rateId: '',
      loginPersonName: '',
      shareTitle: '评价顾问',
      shareQuery: 'consultantId=123'
    };
  },
  created() {
    this.getRateTypeListFn();
  },
  mounted() {
    this.checkLoginStatus();
  },
  onLoad(opt) {
    console.log(opt, '---------');
    // 如果在是通过分享进入的，就需要获取consultantId，这个是针对用户进来页面的逻辑
    this.consultantId = opt.consultantId || undefined;
    // if (this.consultantId) {
    //   this.getConsultantBasicInfoFn();
    // }
  },
  methods: {
    async loginSuccessBack() {
      // 登录成功后，重新获取personId
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      // 先获取登陆人信息
      await this.getUserInfoFn();
      // 获取顾问信息和确定是不是顾问
      await this.getConsultantBasicInfoFn();
      // 获取到rateId
      await this.addConsultantRateFn();
      // await this.checkCardClickable();
    },
    // 获取当前登录人的信息
    async getUserInfoFn() {
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      const res = await getUserInfo({ uid: '' });
      // 如果是顾问进来，就是要把页面分享出去，所以需要把consultantId带上，同时把名字页查找出来显示在上方
      if (res.code == 200) {
        // 如果登录人本身就是顾问，personId就是consultantId;
        const { personId, personName } = res.data;
        this.loginPersonName = personName;
        //复制链接
        wx.onCopyUrl(() => {
          return {
            title: this.shareTitle,
            query: `consultantId=${personId}`
          };
        });
        this.sharePath = `/pagesSub/userCenter/zhituRatePage/index?consultantId=${personId}`;
      }
    },
    async getConsultantBasicInfoFn() {
      // 如果是用户登录，就用consultantId，如果是顾问进来，就用personId；
      const params = {
        consultantId: this.consultantId || this.personId
      };
      const res = await getConsultantBasicInfo(params);
      if (res.code == 200) {
        if (res.data.consultantId) {
          const { consultantPic, consultantName, consultantId } = res.data;
          this.avatar = consultantPic;
          this.consultantName = consultantName;
          this.consultantId = consultantId;
          this.isConsultant = this.personId == this.consultantId ? true : false;
        } else {
          this.consultantName = this.loginPersonName;
        }
      }
    },
    // 获取rateId
    async addConsultantRateFn() {
      const params = {
        consultantId: this.consultantId,
        personId: this.personId,
        chartRoles: this.isConsultant ? '10' : '20'
      };
      const res = await addConsultantRate(params);
      if (res.code == 200) {
        this.rateId = res.data.id;
      }
    },
    //用rateId检查此卡片是否已经评分过
    async checkCardClickable() {
      const params = {
        consultantId: this.consultantId,
        personId: this.personId,
        rateId: this.rateId
      };
      const res = await getConsultantRate(params);
      if (res.code == 200) {
        if (res.data.rateScore) {
          //已经评分过 所以禁用
          this.isRated = true;
          if (res.data.rateList && res.data.rateList.length) {
            this.rateList = res.data.rateList;
          }
          this.handleIconEcho();
        }
      }
    },
    //点击图标处理
    handleRateIconClick(item, index, iconItem, iconIndex) {
      if (!this.personId) {
        this.$refs.uToast.show({
          title: '请先登录！',
          icon: false,
          duration: 1000
        });
        this.showLoginDialog();
        return;
      }
      if (this.isConsultant) {
        //顾问不能评价
        uni.showToast({
          title: '顾问不能自评！',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      //处理变色，存储分数
      item.iconList.forEach((_item, _index) => {
        this.$set(item.iconList, _index, this.grayIconList[_index]);
      });
      this.$set(item.iconList, iconIndex, this.colorIconList[iconIndex]);
      item.rateScore = iconIndex + 1;
    },
    getRateTypeListFn() {
      getRateTypeList().then((res) => {
        this.rateList = res.data;
        this.rateList.forEach((item, index) => {
          this.$set(item, 'iconList', [...this.grayIconList]);
        });
      });
    },
    //请求进行评分
    reqAddConsultantRateDetail() {
      if (!this.personId) {
        this.$refs.uToast.show({
          title: '请先登录！',
          icon: false,
          duration: 1000
        });
        this.showLoginDialog();
        return;
      }
      //顾问不能评价
      if (this.isConsultant) {
        uni.showToast({
          title: '顾问不能自评！',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      const temp = this.rateList.find((_item) => {
        //后端返回的有可能为0
        return _item.rateScore == undefined || _item.rateScore <= 0;
      });
      if (temp) {
        this.$refs.uToast.show({
          title: '请先完成满意度评分！',
          icon: false,
          duration: 1500
        });
        return;
      }
      let urlArr = [];
      this.photosArray.forEach((item) => {
        urlArr.push(`http://img106.job1001.com/${item.response}`);
      });
      const params = {
        rateList: this.rateList,
        rateId: this.rateId,
        content: this.content,
        contact: this.contact,
        photos: urlArr.join(',')
      };
      addConsultantRateDetail(params).then((res) => {
        if (res.code == 200) {
          this.isRated = true;
          this.$refs.uToast.show({
            title: '评价成功',
            icon: false,
            url: '/pagesSub/userCenter/careerPathV2/index',
            duration: 1000
          });
        } else {
          this.$refs.uToast.show({
            title: '服务期开小差啦~',
            icon: false,
            duration: 1200
          });
        }
      });
    },
    //回显已经选过分数的icon
    handleIconEcho() {
      this.rateList.forEach((item, index) => {
        item.iconList = this.grayIconList.map((_item, _index) => {
          if (_index == item.rateScore - 1) {
            return this.colorIconList[_index];
          } else {
            return _item;
          }
        });
      });
    },
    onPageScroll(res) {
      this.showTop = res.scrollTop > 0;
    },
    beforeUpload(index, list) {
      if (list[index].file.size > 4 * 1024 * 1024) {
        uni.showToast({
          title: '图片大小不能超过4M',
          icon: 'none',
          duration: 1000
        });
        list.splice(index, 1);
        return false;
      }
      return true;
    },
    onUploaded(lists) {
      this.photosArray = lists;
    },
    checkLoginStatus() {
      // 检查登录状态，如果登录就登录
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }
      // 如果登录了就直接调用登录成功回调
      this.loginSuccessBack();
    },
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    }
  }
};
</script>

<style lang="scss" scoped>
.out-wrapper {
  display: flex;
  flex-direction: column;
  position: relative;
  background-image: url($img-base + 'careerPath/pageBg.png');
  background-size: 100% 832rpx;
  background-repeat: no-repeat;
  min-height: 100vh;
  overflow-y: auto;
  padding-bottom: calc(130rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(130rpx + env(safe-area-inset-bottom));
  .header-wrapper {
    margin: 0 16rpx;
    background-color: #fff;
    border-radius: 8rpx;
    .header {
      .question {
        font-size: 36rpx;
        padding: 36rpx 0 42rpx 32rpx;
        color: #333;
      }
      .consultant-info {
        display: flex;
        align-items: center;
        padding: 0 28rpx 32rpx 28rpx;
        border-bottom: 2rpx solid #f4f4f4;
        .avatar-box {
          .avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 18px;
          }
        }
        .name-box {
          .consultant-name {
            color: #222;
            font-size: 32rpx;
            margin-bottom: 4rpx;
          }
          .finish-date {
            font-size: 24rpx;
            color: #888;
          }
        }
      }
    }
    .rateCardContent {
      display: flex;
      flex-direction: column;
      margin: 32rpx 0 58rpx 0;
      .rateTitleRow {
        display: flex;
        font-size: 24rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #888888;
        line-height: 46rpx;
        text-align: center;
        margin-bottom: 20rpx;
        .rateTitleCol {
          width: calc(100% / 24 * 4);

          &:nth-of-type(1) {
            width: calc(100% / 24 * 5);
          }
        }
      }
      .rateContentRow {
        display: flex;
        font-size: 30rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 46rpx;
        text-align: center;
        padding: 29rpx 0;
        .rateContentCol {
          display: flex;
          justify-content: center;
          align-items: center;
          width: calc(100% / 24 * 4);
          .rateContentIcon {
            width: 48rpx;
            height: 48rpx;
          }
          &:nth-of-type(1) {
            width: calc(100% / 24 * 5);
          }
        }
      }
    }
  }
  .box {
    margin: 20rpx 16rpx 0 16rpx;
    background-color: #fff;
    border-radius: 8rpx;
    .title {
      padding: 34rpx 0 0 32rpx;
      font-size: 30rpx;
      color: #333;
      .small {
        font-size: 28rpx;
        color: #999;
        margin-left: 20rpx;
      }
    }
    ::v-deep .u-field {
      padding: 20rpx 2rpx 20rpx 20rpx;
    }
  }
  .callback-wrapper {
    .upload-wrap {
      color: $uni-text-color-333;
      padding: 20rpx 28rpx;
      .slot-btn {
        height: 220rpx;
        width: 220rpx;
        padding: 20rpx;
        line-height: 1;
        font-size: 24rpx;
        color: #666;
        border-radius: $uni-border-radius-lg;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #fafafa;
      }
      .upload-img {
        display: inline-block;
        margin-bottom: 10rpx;
        width: 80rpx;
        height: 70rpx;
      }
      .tips {
        font-size: $uni-font-size-sm;
        color: $uni-text-color-999;
        margin-top: 18rpx;
      }
    }
  }
  .number-wrapper {
  }
}
.btn-bar {
  width: 100vw;
  display: flex;
  justify-content: center;
  padding: 0 32rpx;
  position: fixed;
  padding-bottom: calc(5rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(5rpx + env(safe-area-inset-bottom));
  bottom: 0;
  left: 0;
  z-index: 999;
}
</style>
